/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：网络通信管理器，实现局域网通信
* CreateTime：2021-01-15 20:56:09
* Version：1.0
* Modify Recorder：
*************************************************/

using System;
using System.Net;

namespace TinyToolKit.Network
{
    public class TNetworkManager : ManagerBase
    {
        private NetworkDiscoveryHelper _networkDiscoveryHelper;
        private TcpServerHelper _tcpServerHelper;
        private TcpClientHelper _tcpClientHelper;

        #region Manager Func

        public override void Init()
        {
        }

        public override void UpdateManager()
        {
            _tcpClientHelper?.Update();
        }

        public override void Shutdown()
        {
            _networkDiscoveryHelper?.CloseBroadcast();
            _networkDiscoveryHelper?.CloseReceive();
            _tcpClientHelper?.Close();
            _tcpServerHelper?.Close();
        }

        #endregion

        #region Public Func

        /// <summary>
        /// 创建网络查询辅助类
        /// </summary>
        /// <returns>返回网络查询辅助类</returns>
        public NetworkDiscoveryHelper CreateNetworkDiscovery()
        {
            _networkDiscoveryHelper = new NetworkDiscoveryHelper();
            return _networkDiscoveryHelper;
        }

        /// <summary>
        /// 创建并开启服务器
        /// </summary>
        /// <param name="ip">服务器IP地址</param>
        /// <param name="port">端口号</param>
        /// <param name="maxConnCount">服务器最大连接数</param>
        /// <param name="tcpServerHelper">返回服务器的辅助类</param>
        /// <param name="connectClientCb">客户端连接时的回调函数</param>
        /// <param name="disconnectClientCb">客户端断开连接时的回调函数</param>
        /// <returns>判断是否创建成功</returns>
        public bool CreateTcpServer(string ip, int port, int maxConnCount, out TcpServerHelper tcpServerHelper, Action<IPEndPoint> connectClientCb = null, Action<IPEndPoint> disconnectClientCb = null)
        {
            _tcpServerHelper = new TcpServerHelper();
            if (_tcpServerHelper.Start(ip, port, maxConnCount, connectClientCb, disconnectClientCb))
            {
                tcpServerHelper = _tcpServerHelper;
                return true;
            }

            _tcpServerHelper = null;
            tcpServerHelper = null;
            return false;
        }

        public bool CreateTcpClient(string ip, int port,out TcpClientHelper tcpClientHelper,Action successConnectCb = null,Action interruptConnectCb = null)
        {
            _tcpClientHelper = new TcpClientHelper();
            if(_tcpClientHelper.Connect(ip, port,successConnectCb,interruptConnectCb)) 
            {
                tcpClientHelper = _tcpClientHelper;
                return true;
            }

            _tcpClientHelper = null;
            tcpClientHelper = null;
            return false;
        }

        #endregion
    }
}